#!/usr/bin/python
# -*-coding:utf-8-*-
# pip install ddddocr 图片识别
"""农产品质量追溯管理平台_生产档案/企业自检/追溯批次/入市追溯/督查巡查/产品抽检/标签打印/合格证"""
import time
import requests
import json
from time import sleep
import common
import db
import pymongo
import sys
from dotenv import load_dotenv, find_dotenv
import os
import asyncio
from pyppeteer import launch
import numpy as np
import pandas as pd

mysqldb = db.DbManager()

load_dotenv(verbose=True)
# 今天
today_time = common.TodayTime()
# 将-替换为.
today_time_new = today_time.replace('-', '.')
# 账号
username = os.getenv('ADMIN')
passworld = os.getenv('PWD')

# 获取登录后cookie
async def get_cookie(page):
    cookies_list = await page.cookies()
    cookies = ''
    for cookie in cookies_list:
        str_cookie = '{0}={1};'
        str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value'))
        cookies += str_cookie
    print(cookies)
    return cookies





def list_split(items, n):
    return [items[i:i + n] for i in range(0, len(items), n)]


def curl(orgId):
    for k in ['pageProduceRecordForReg', 'pageDetectionForReg', 'pageInventoryForReg', 'pageSoldRecordForReg',
              'pagePatrolFromOrg', 'pageProductCheckFromOrg', 'pagePrintRecordForOrg', 'pageHgzPrintRecordForOrg']:
        # pageProduceRecordForReg/生产档案 pageDetectionForReg/企业自检 pageInventoryForReg/批次追溯 pageSoldRecordForReg/入市追溯 pagePatrolFromOrg/督查巡查 pageProductCheckFromOrg/产品抽检 pagePrintRecordForOrg/标签打印 pageHgzPrintRecordForOrg/合格证
        url_type={'pageProduceRecordForReg':"main_print_record","pageDetectionForReg":"main_detection","pageInventoryForReg":"main_inventory","pageSoldRecordForReg":"main_sold_record","pagePatrolFromOrg":"main_patrol_from","pageProductCheckFromOrg":"main_produce_check","pagePrintRecordForOrg":"main_print","pageHgzPrintRecordForOrg":"main_produce_hgz"}
        url_id={'pageProduceRecordForReg':"produce_record_id","pageDetectionForReg":"detection_id","pageInventoryForReg":"inventory_id","pageSoldRecordForReg":"sold_record_id","pagePatrolFromOrg":"patrol_id","pageProductCheckFromOrg":"product_check_id","pagePrintRecordForOrg":"print_record_id","pageHgzPrintRecordForOrg":"print_record_id"}
        url_oid={'pageProduceRecordForReg':"produceRecordId","pageDetectionForReg":"detectionId","pageInventoryForReg":"inventoryId","pageSoldRecordForReg":"soldRecordId","pagePatrolFromOrg":"patrolId","pageProductCheckFromOrg":"productCheckId","pagePrintRecordForOrg":"printRecordId","pageHgzPrintRecordForOrg":"printRecordId"}
        # 生产档案
        with open("cookie.txt", 'r') as file:
            a = file.read()
            a2 = a.split("&&")
        print(a2)
        new_cookie=a2[0]
        new_token=a2[1]
        cookie_str = new_cookie
        cookie_str = cookie_str.encode("utf-8").decode("latin1")
        cookie_list = cookie_str.split('; ')
        cookies = {cookies.split('=')[0]: cookies.split('=')[-1] for cookies in cookie_str.split('; ')}
        headers = {
            'referer': 'https://zs.jsncpaq.com/jg/insideForm/mainDetail.html?orgId=' + str(orgId),
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36',
            'token': new_token,
            'x-token': new_token,
        }
        resp = requests.get(
            "https://zs.jsncpaq.com/tracewebapp/desk/reg/"+str(k)+".do?orgId=" + str(
                orgId) + "&pageNo=1&pageSize=100",
            headers=headers, cookies=cookies)
        print("----------")
        print(resp)
        print("----------")
        json_text = json.loads(resp.text)
        print(json_text)
        list_html_list = json_text['rows']
        print(len(list_html_list))
        if len(list_html_list)==0:
            info={"orgId": orgId}
            if url_type[k]=='main_print_record':
                mysqldb.table_insert(table=url_type[k], data=info)
            continue
        for i in range(0,len(list_html_list)):
            print(url_type[k])
            info={}
            list_html=list_html_list[i]
            if k =='pageProduceRecordForReg':
                # 生产档案
                if list_html['isEdit']==1:
                    status_str="生产中"
                else:
                    status_str = "其他"
                info = {"orgId": orgId, "produce_record_no": list_html['produceRecordNo'],
                        "produce_record_name": list_html['productName'],
                        'batch_no': list_html['batchNo'], 'produce_time': list_html['produceTime'],
                        'status_str':status_str, 'produce_worker_name': list_html['produceWorkerName'],url_id[k]:list_html[url_oid[k]]}
            elif k =='pageDetectionForReg':
                # 企业自检
                if list_html['detectionResult']==1:
                    status_str="合格"
                else:
                    status_str = "其他"
                info = {"orgId": orgId, "detection_desc": status_str,
                        "checker_name": list_html['customProductName'],
                        "detection_type_name": list_html['detectionTypeName'],
                        "detection_time": list_html['detectionTime'],
                        "state": list_html['state'],
                        'detectioner': list_html['detectioner'],url_id[k]:list_html[url_oid[k]]}
            elif k=='pageInventoryForReg':
                # 追溯批次
                info = {"orgId": orgId, "product_name": list_html['productName'],
                        "trace_code": list_html['traceCode'],
                        "product_class_name": list_html['productClassName'],
                        "unit_name": list_html['unitName'],
                        "stock": list_html['stock'],
                        "sold_num": list_html['soldNum'],
                        "num": list_html['num'],
                        "froms_name": list_html['fromsName'],
                        "input_time": list_html['inputTime'],
                        "detection_desc": list_html['detectionDesc'],url_id[k]:list_html[url_oid[k]]}
            elif k=='pageSoldRecordForReg':
                # 入市追溯
                info = {"orgId": orgId, "product_name": list_html['productName'],
                        "product_class_name": list_html['productClassName'],
                        "sold_time": list_html['soldTime'],
                        "num": list_html['num'],
                        "unit_name": list_html['unitName'],
                        "market_trace_code": list_html['marketTraceCode'],
                        "state": list_html['state'],
                        url_id[k]:list_html[url_oid[k]],
                        }
            elif k=='pagePatrolFromOrg':
                # 督查巡查
                if list_html['result']==1:
                    result_str="合格"
                else:
                    result_str = "其他"
                info = {"orgId": orgId, "regulatory_name": list_html['regulatoryObjName'],
                        "patrol_reg_names": list_html['patrolRegNames'],
                        "patrol_reg_time": list_html['patrolTime'],
                        "patrol_worker_name": list_html['patrolWorkerNames'],
                        "result": list_html['result'],
                        "result_str": result_str,
                        url_id[k]:list_html[url_oid[k]],
                        }
            elif k=='pageProductCheckFromOrg':
                # 产品抽查
                if list_html['result']==1:
                    result_str="合格"
                else:
                    result_str = "其他"
                info = {"orgId": orgId, "check_product_names": list_html['checkProductNames'],
                        "name": list_html['regulatoryObjName'],
                        "check_reg_name": list_html['checkRegName'],
                        "check_time": list_html['checkTime'],
                        "check_worker_names": list_html['checkWorkerNames'],
                        "result":list_html['result'],
                        "result_str": result_str,
                        url_id[k]:list_html[url_oid[k]],
                        }
            elif k=='pagePrintRecordForOrg':
                # 标签打印
                info = {"orgId": orgId, "org_name": list_html['orgName'],
                        "product_name": list_html['productName'],
                        "trace_code": list_html['traceCode'],
                        "create_time": list_html['createTime'],
                        "count": list_html['count'],
                        url_id[k]:list_html[url_oid[k]],
                        }
            elif k=='pageHgzPrintRecordForOrg':
                # 合格证
                info = {"orgId": orgId,"org_name":list_html['orgName'], "product_name": list_html['productName'],
                        "trace_code": list_html['traceCode'],
                        "count": list_html['count'],
                        "source_one_weight": list_html['sourceOneWeight'],
                        "unit_name": list_html['unitName'],
                        "create_time": list_html['createTime'],
                        url_id[k]:list_html[url_oid[k]],
                        }
            else:
                print("url不正确")
            print(info)
            if k in ['pagePrintRecordForOrg','pageHgzPrintRecordForOrg']:
                find_info = mysqldb.table_select_one(table=url_type[k], field="id", where={"orgId": orgId,url_id[k]:list_html[url_oid[k]],"org_name":list_html['orgName']})
            else:
                find_info = mysqldb.table_select_one(table=url_type[k], field="id",
                                                     where={"orgId": orgId, url_id[k]: list_html[url_oid[k]]})

            # 存在数据则跳过
            if find_info:
                print(str(orgId) + " 已存在数据 跳过")
                continue
            mysqldb.table_insert(table=url_type[k], data=info)
        sleep(2)


class Egas:
    def __init__(self):
        self.url = "http://zs.jsncpaq.com/"
        sql = 'SELECT i.orgId FROM main_info as i left join main_print_record as r on r.orgId=i.orgId where i.orgId >0 and r.orgId is null order by register_time desc,i.orgId desc limit 500'
        # sql = 'SELECT i.orgId FROM main_info as i left join main_print_record as r on r.orgId=i.orgId where i.orgId=866723562457661440 limit 500'
        mysqldb.execute(sql)
        self.org_ids=mysqldb.cur.fetchall()
        asyncio.get_event_loop().run_until_complete(self.main())

    async def main(self):
        # 将数组 list1 每 3 个切分一次
        list2 = list_split(self.org_ids, 2)
        print(list2)
        for i in range(len(list2)):
            # pageProduceRecordForReg/生产档案 pageDetectionForReg/企业自检 pageInventoryForReg/批次追溯 pageSoldRecordForReg/入市追溯 pagePatrolFromOrg/督查巡查 pageProductCheckFromOrg/产品抽检 pagePrintRecordForOrg/标签打印 pageHgzPrintRecordForOrg/合格证
            for key in range(len(list2[i])):
                print(list2[i][key]['orgId'])
                curl(list2[i][key]['orgId'])
Egas()
